﻿using Ookii.Dialogs.Wpf;
using PLCS.App.Shared.Extensions;
using PLCS.Application.Contracts.StationApp.Dtos;
using PLCS.Application.Contracts.TrayApp.Dtos;
using PLCS.Domain.Shared.Stations;
using System.Threading.Tasks;

namespace PLCS.App.EquipmentManager.ViewModels.Tray;

public class TrayViewModel : NavigationPagedCurdViewModel<TrayDto, TrayEditDto, ITrayService>
{
    private string _trayNo, _trayType;

    public string TrayNo
    {
        get { return _trayNo; }
        set { SetProperty(ref _trayNo, value); }
    }

    public string TrayType
    {
        get { return _trayType; }
        set { SetProperty(ref _trayType, value); }
    }

    public DelegateCommand ImportCommand { get; set; }

    public override async Task GetPageData(int pageIndex)
    {
        try
        {
            UpdateLoading(true);
            var res = await _service.GetListBySearchAsync((pageIndex - 1) * PageSize, PageSize, TrayType, TrayNo);
            TotalCount = (int)res.TotalCount;
            SetPageCount();
            DataGridList = res.Items.ToObservable();
        }
        finally
        {
            UpdateLoading(false);
        }
    }

    private async void Import()
    {
        try
        {
            var fileDialog = new VistaOpenFileDialog();
            fileDialog.ShowDialog();

            var fileName = fileDialog.FileName;

            if (fileName == null)
                return;

            // 读取excel导入到DataTable
            var table = TableHelper.ExcelToTable(fileName);

            if (table == null) return;
            // 将DataTable转为list
            var trayDtos = table.ToList<TrayEditDto>();
            // 开始导入
            await _service.CreateListAsync(trayDtos);

            ShowMessage("导入成功");
            // 导入完刷新
            await RefreshAsync();
        }
        catch (System.Exception ex)
        {
            ShowMessage(ex.Message);
        }
    }

    public TrayViewModel(ITrayService service) : base(service)
    {
        ImportCommand = new DelegateCommand(Import);
    }
}